package com.example.gpssystem.service;

import com.example.gpssystem.model.Address;
import com.example.gpssystem.repository.mongo.AddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class AddressService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String ADDRESS_KEY = "common_addresses";
    @Autowired
    private AddressRepository addressRepository;

    private List<String> queryFromDatabase(String userId) {
        List<Address> addresses = addressRepository.findByUserId(userId);
        return addresses.stream()
                .sorted(Comparator.comparing(Address::isDefault).reversed())
                .map(Address::getAddress)
                .collect(Collectors.toList());
    }

    @CacheEvict(value = ADDRESS_KEY, key = "#userId")
    public void addCommonAddress(String userId, String address) {
        Address newAddress = new Address();
        newAddress.setUserId(userId);
        newAddress.setAddress(address);
        newAddress.setCreateTime(LocalDateTime.now());
        newAddress.setDefault(false);
        addressRepository.save(newAddress);
    }

    @CacheEvict(value = ADDRESS_KEY, key = "#userId")
    public void deleteAddress(String userId, String address) {
        addressRepository.deleteByUserIdAndAddress(userId, address);
    }
    @Cacheable(value = ADDRESS_KEY, key = "#userId")
    public List<String> getCommonAddresses(String userId) {
        // 先查缓存
        List<Object> cached = redisTemplate.opsForList().range(ADDRESS_KEY + userId, 0, -1);
        if (cached != null && !cached.isEmpty()) {
            return cached.stream().map(Object::toString).collect(Collectors.toList());
        }

        // 缓存未命中，查询数据库（示例实现）
        List<String> addresses = queryFromDatabase(userId);

        // 写入缓存
        if (!addresses.isEmpty()) {
            redisTemplate.opsForList().rightPushAll(ADDRESS_KEY + userId, addresses);
            redisTemplate.expire(ADDRESS_KEY + userId, 1, TimeUnit.HOURS);
        }
        return addresses;
    }
}


